package com.wanjia.estate.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.wanjia.estate.constant.DocumentType;
import com.wanjia.estate.exception.ControllerException;
import com.wanjia.estate.pojo.bdc.SetDzcl;
import com.wanjia.estate.properties.FolderPathProperties;
import com.wanjia.estate.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


@Service
@Slf4j
public class DzclAddDataService {

    @Autowired
    FolderPathProperties folderPathProperties;

    public List<SetDzcl.Ywdzcl> DzclAddData(String clmc, String prefix){
        String pdfpath = folderPathProperties.getPdfpath();
        String dirname = DocumentType.getByClmc(clmc).dir();
        String clmcpath=pdfpath+"/"+dirname;
        log.info("图片文件路径：{}",clmcpath);
        File folder = new File(clmcpath);

        if (!folder.exists() || !folder.isDirectory()) {
            throw new ControllerException("一窗电子材料的文件夹不存在");
        }

        File[] imageFiles = folder.listFiles();

        if (imageFiles==null){
            throw new ControllerException("一窗电子材料的图片不存在");
        }

        List<SetDzcl.Ywdzcl> ywdzclList=new ArrayList<>();
        for (File imageFile : imageFiles) {
            try {
                SetDzcl.Ywdzcl ywdzcl=new SetDzcl.Ywdzcl();
                SetDzcl.Ywdzclwj ywdzclwj = new SetDzcl.Ywdzclwj();
                String base64String = convertToBase64(imageFile);
                ywdzclwj.setDzcl(base64String);
                ywdzcl.setYwdzclwj(ywdzclwj);
                ywdzcl.setWjlj(StrUtil.nullToEmpty(prefix) + imageFile.getName());
                ywdzclList.add(ywdzcl);
//                log.info("文件名: {}",imageFile.getName());
//                log.info("Base64编码: {}",base64String);
//                log.info("-----------------------------------");
            } catch (IOException e) {
                log.info("处理文件时出现错误：{}", e.getMessage());
            }
        }
        return ywdzclList;
    }

    private static String convertToBase64(File file) throws IOException {
        try (FileInputStream inputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            inputStream.read(bytes);
            return Base64.getEncoder().encodeToString(bytes);
        }
    }

}
